import time
from rpyc import Service
from rpyc.utils.server import ThreadedServer

from task_scheduler import sched

def new_process(spider_name):
    from manage import run_spider
    import os

    print('pid: ', os.getpid())
    print('ppid: ', os.getppid())

    run_spider(spider_name)

    return os.getpid()

class TimeService(Service):
    # 对于服务端来说， 只有以"exposed_"打头的方法才能被客户端调用，
    # 所以要提供给客户端的方法都得加"exposed_"
    def exposed_get_time(self):
        return time.ctime()      #time模块中的一个内置方法
    
    def exposed_hello(self, name='无名氏'):
        return '你好: ' + name

    def exposed_run_spider(self, spider_name):
        import multiprocessing
        p = multiprocessing.Process(
            name='xiaoshuo-spider',
            target=new_process,
            args=('booktxt',),
            daemon=False
        )
        p.start()
        p.join()
        '''
        from datetime import datetime, timedelta
        job = sched.add_job(
            run_spider,
            'date',
            run_date=datetime.now() + timedelta(seconds=1),
            args=(spider_name,)
        )
        '''
        return '你好: ' + spider_name

def start_task_server():
    s=ThreadedServer(
        service=TimeService,
        port=12233,
        auto_register=False
    )
    s.start()